package com.hethongviet.vending.helper.db;

import java.util.ArrayList;
import java.util.List;

import com.hethongviet.vending.Utils;
import com.hethongviet.vending.model.ProductService;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class ProductServiceSQLite
{
	public static final String TABLE_NAME = "product_service";

	public static final String COLUMN_ID_DB = "idDB";

	public static final String COLUMN_ID_BOX = "id_box";
	public static final String COLUMN_CODE_PRODUCT = "code_product";
	public static final String COLUMN_STAFF_SERVICE = "staff_service";
	public static final String COLUMN_STAFF_CHECKER = "staff_checker";

	public static final String COLUMN_PRICE = "price";
	public static final String COLUMN_IS_SENT_SERVER_OK = "sent_server";
	public static final String COLUMN_DATE = "date";
	public static final String COLUMN_TRANSACTION = "transaction_";
	public static final String COLUMN_AMOUNT = "amount";

	// Database fields
	private SQLiteDatabase _database;
	private MySQLiteHelper _dbHelper;

	private String[] _allColumns = { COLUMN_ID_DB, COLUMN_ID_BOX,
			COLUMN_CODE_PRODUCT, COLUMN_DATE, COLUMN_PRICE,
			COLUMN_IS_SENT_SERVER_OK, COLUMN_STAFF_CHECKER,
			COLUMN_STAFF_SERVICE, COLUMN_TRANSACTION, COLUMN_AMOUNT };

	public static final String STRING_COLUMNS = COLUMN_ID_DB
			+ " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, "
			+ COLUMN_ID_BOX + " text, " + COLUMN_CODE_PRODUCT + " text, "
			+ COLUMN_DATE + " text, " + COLUMN_PRICE + " text, "
			+ COLUMN_IS_SENT_SERVER_OK + " integer, " + COLUMN_STAFF_CHECKER
			+ " text, " + COLUMN_STAFF_SERVICE + " text, " + COLUMN_TRANSACTION
			+ " integer, " + COLUMN_AMOUNT + " integer";

	public ProductServiceSQLite(Context context)
	{
		_dbHelper = new MySQLiteHelper(context, null, null);
	}

	public void open() throws SQLException
	{
		_database = _dbHelper.getWritableDatabase();
	}

	public void close()
	{
		_dbHelper.close();
	}

	private boolean dataExist(ProductService productService, Cursor cursor)
	{
		if (cursor == null)
		{
			return false;
		}
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
		{
			long idDB = cursor.getLong(cursor.getColumnIndex(COLUMN_ID_DB));
			if (idDB == productService.getIdDB())
				return true;
		}
		return false;
	}

	/**
	 * @param productService
	 * @return row id -1: insert fail
	 */
	public long insert(ProductService productService)
	{
		open();

		Utils.debug("insert -- " + productService.getIdBox());
		Cursor cursor = _database.rawQuery("SELECT * FROM " + TABLE_NAME
				+ " WHERE " + COLUMN_ID_DB + " = " + productService.getIdDB(),
				null);

		long temp = -1;
		if (!dataExist(productService, cursor))
		{
			Utils.debug("insert 1111111111111 INSERT");
			/* Insert to database */
			/* Insert new */
			Cursor cursorInsert = _database.rawQuery(
					"INSERT INTO " + TABLE_NAME + "("

					+ COLUMN_ID_BOX + ", " + COLUMN_CODE_PRODUCT + ", "
							+ COLUMN_DATE + ", " + COLUMN_PRICE + ", "
							+ COLUMN_IS_SENT_SERVER_OK + ", "

							+ COLUMN_STAFF_CHECKER + ", "
							+ COLUMN_STAFF_SERVICE + ", " + COLUMN_TRANSACTION
							+ ", " + COLUMN_AMOUNT
							+ ") values( ?, ?, ?, ?, ?, ?, ?, ?, ?)",

					new String[] { productService.getIdBox() + "",
							productService.getCodeProduct(),
							productService.getDate() + "",
							productService.getPrice() + "",
							productService.isSentServerOk() ? "1" : "0",
							productService.getStaffChecker(),
							productService.getStaffService(),
							productService.getTransaction() + "",
							productService.getAmount() + "" });

			cursorInsert.moveToFirst();
			if (!cursorInsert.isAfterLast())
				temp = cursorInsert.getLong(cursorInsert.getColumnIndex(COLUMN_ID_DB));

			cursorInsert.close();
		}
		else
		{
			Utils.debug("insert 1111111111111 update");
			/* Update to database */
			Cursor cursorUpdate = _database.rawQuery(
					"UPDATE " + TABLE_NAME + " SET " + COLUMN_ID_BOX + " = ?, "
							+ COLUMN_CODE_PRODUCT + " = ?, " + COLUMN_DATE
							+ " = ?, " + COLUMN_PRICE + " = ?, "
							+ COLUMN_IS_SENT_SERVER_OK + " = ?, "
							+ COLUMN_STAFF_CHECKER + " = ?, "
							+ COLUMN_STAFF_SERVICE + " = ?, "
							+ COLUMN_TRANSACTION + " = ?, " + COLUMN_AMOUNT
							+ " = ? " + "WHERE " + COLUMN_ID_DB + " = "
							+ productService.getIdDB(),

					new String[] { productService.getIdBox() + "",
							productService.getCodeProduct(),
							productService.getDate() + "",
							productService.getPrice() + "",
							productService.isSentServerOk() ? "1" : "0",
							productService.getStaffChecker(),
							productService.getStaffService(),
							productService.getTransaction() + "",
							productService.getAmount() + "" });
			cursorUpdate.moveToFirst();
			if (!cursorUpdate.isAfterLast())
				temp = cursorUpdate.getLong(cursorUpdate.getColumnIndex(COLUMN_ID_DB));

			cursorUpdate.close();
		}
		cursor.close();
		close();
		return temp;
	}

	public void deleteAll()
	{
		open();

		System.out.println("project deleted all");
		// _database.rawQuery("DELETE FROM " + TABLE_NAME, null); not work
		// _database.rawQuery("DELETE FROM " + TABLE_NAME + " WHERE 1", null);
		_database.delete(TABLE_NAME, "1", null);
		close();
	}

	public List<ProductService> getAll()
	{
		open();

		List<ProductService> listProductServices = new ArrayList<ProductService>();

		Cursor cursor = _database.query(TABLE_NAME, _allColumns, null, null,
				null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast())
		{
			ProductService productService = cursorToProductService(cursor);
			listProductServices.add(productService);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		close();
		return listProductServices;
	}

	private ProductService cursorToProductService(Cursor cursor)
	{
		ProductService productService = new ProductService();
		productService.setIdDB(cursor.getLong(cursor.getColumnIndex(COLUMN_ID_DB)));
		productService.setIdBox(cursor.getInt(cursor.getColumnIndex(COLUMN_ID_BOX)));
		productService.setCodeProduct(cursor.getString(cursor.getColumnIndex(COLUMN_CODE_PRODUCT)));

		String dateString = cursor.getString(cursor.getColumnIndex(COLUMN_DATE));
		long date = -1;
		try
		{
			date = Long.parseLong(dateString);
		} catch (NumberFormatException e)
		{
			e.printStackTrace();
		}
		productService.setDate(date);

		productService.setPrice(cursor.getInt(cursor.getColumnIndex(COLUMN_PRICE)));
		productService.setSentServerOk(cursor.getInt(cursor.getColumnIndex(COLUMN_IS_SENT_SERVER_OK)) == 1);
		productService.setStaffChecker(cursor.getString(cursor.getColumnIndex(COLUMN_STAFF_CHECKER)));
		productService.setStaffService(cursor.getString(cursor.getColumnIndex(COLUMN_STAFF_SERVICE)));

		int transactionType = cursor.getInt(cursor.getColumnIndex(COLUMN_TRANSACTION));
		if (transactionType != ProductService.TRANSACTION_PRODUCT_PUT_IN
				&& transactionType != ProductService.TRANSACTION_PRODUCT_TAKE_OUT)
		{
			transactionType = ProductService.TRANSACTION_PRODUCT_PUT_IN;
		}
		productService.setTransaction(transactionType);

		productService.setAmount(cursor.getInt(cursor.getColumnIndex(COLUMN_AMOUNT)));

		return productService;
	}

	public void updateIdDB(ProductService productService)
	{
		open();

		Utils.debug("1111111111111 update box id DB = "
				+ productService.getIdBox());
		/* Update to database */
		Cursor cursor = _database.query(TABLE_NAME, _allColumns, null, null,
				null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast())
		{
			ProductService productServiceGet = cursorToProductService(cursor);
			if (productServiceGet.getDate() == productService.getDate())
			{
				productService.setIdDB(productServiceGet.getIdDB());
				break;
			}
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		close();
	}

	public final boolean isTableExist()
	{
		open();

		boolean isExist = false;
		Cursor cursor = _database.rawQuery(
				"select DISTINCT tbl_name from sqlite_master where tbl_name = '"
						+ TABLE_NAME + "'", null);
		isExist = cursor != null && cursor.getCount() > 0;

		cursor.close();
		close();

		return isExist;
	}
}
